import React, { useEffect } from 'react';

function ajax(url) {
  return new Promise(function (resolve, reject) {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url);
    xhr.responseType = 'json';
    xhr.onload = function () {
      switch (this.status) {
        case 200:
          resolve(this.response);
          break;
        case 404:
          reject(new Error('找不到的异常'));
          break;
        default:
          reject(new Error(this.statusText));
          break;
      }
    };
    xhr.send();
  });
}

function* model() {
  const { data: user } = yield ajax('http://localhost:3001/api/userData');
  console.log(user);

  const { data: post } = yield ajax('http://localhost:3001/api/postData');
  console.log(post);

  const err = yield ajax('/api/errData');
  console.log(err);
}

function co(generator, params) {
  const step = generator.next(params);
  const { value, done } = step;
  if (done) return;
  value.then(
    data => {
      co(generator, data);
    },
    e => {
      generator.throw(e);
    },
  );
}

function main() {
  co(model());
}

export default function Increase() {
  useEffect(main, []);

  return (
    <div>
      <p>Promise 用例改进</p>
    </div>
  );
}
